<template>
  <view class="login-container">
    <!-- 背景装饰 -->
    <view class="bg-decoration"></view>

    <!-- 登录表单 -->
    <view class="login-form">
      <!-- Logo区域 -->
      <view class="logo-section">
        <view class="logo">云狐AI</view>
        <view class="subtitle">智能AI助手</view>
      </view>

      <!-- 登录模式选择 -->
      <!-- <view v-if="currentMode === 'login'" class="login-type-section">
        <view class="type-btn" :class="{ active: loginType === 'mobile' }" @click="switchLoginType('mobile')">
          手机号登录
        </view>
        <view class="type-btn" :class="{ active: loginType === 'account' }" @click="switchLoginType('account')">
          账号登录
        </view>
      </view> -->

      <!-- 手机号登录表单 -->
      <view v-if="currentMode === 'login' && loginType === 'mobile'" class="input-section">
        <!-- 手机号输入 -->
        <view class="input-group">
          <view class="input-wrapper">
            <text class="country-code">+ 86</text>
            <input class="phone-input" type="number" v-model="phone" placeholder="请输入手机号" maxlength="11" />
          </view>
        </view>

        <!-- 验证码输入 -->
        <view class="input-group">
          <view class="input-wrapper">
            <input class="code-input" type="number" v-model="code" placeholder="请输入验证码" maxlength="4" />
            <view class="code-btn" @click="sendCode">
              {{ codeText }}
            </view>
          </view>
        </view>

        <!-- 登录按钮 -->
        <view class="login-btn-wrapper">
          <button class="login-btn" @click="handleMobileLogin">
            登录
          </button>
          <view class="switch-btn" @click="switchMode('register')">
            注册
          </view>
        </view>
      </view>

      <!-- 账号登录表单 -->
      <view v-if="currentMode === 'login' && loginType === 'account'" class="input-section">
        <!-- 用户名输入 -->
        <view class="input-group">
          <view class="input-wrapper">
            <input class="text-input" type="text" v-model="username" placeholder="请输入用户名" />
          </view>
        </view>

        <!-- 密码输入 -->
        <view class="input-group">
          <view class="input-wrapper">
            <input class="text-input" type="password" v-model="password" placeholder="请输入密码" />
          </view>
        </view>

        <!-- 图形验证码 -->
        <view class="input-group">
          <view class="input-wrapper">
            <input class="code-input" type="text" v-model="captchaCode" placeholder="请输入验证码" maxlength="4" />
            <view class="captcha-img" @click="refreshCaptcha">
              <image v-if="captchaImage" :src="captchaImage" mode="aspectFit" />
              <text v-else>获取验证码</text>
            </view>
          </view>
        </view>

        <!-- 登录按钮 -->
        <view class="login-btn-wrapper">
          <button class="login-btn" @click="handleAccountLogin">
            登录
          </button>
          <view class="switch-btn" @click="switchMode('register')">
            注册
          </view>
        </view>
      </view>

      <!-- 注册表单 -->
      <view v-if="currentMode === 'register'" class="input-section">
        <!-- 用户名输入 -->
        <view class="input-group">
          <view class="input-wrapper">
            <input class="text-input" type="text" v-model="regUsername" placeholder="请输入用户名" />
          </view>
        </view>

        <!-- 密码输入 -->
        <view class="input-group">
          <view class="input-wrapper">
            <input class="text-input" type="password" v-model="regPassword" placeholder="请输入密码" />
          </view>
        </view>

        <!-- 手机号输入 -->
        <view class="input-group">
          <view class="input-wrapper">
            <text class="country-code">+ 86</text>
            <input class="phone-input" type="number" v-model="regPhone" placeholder="请输入手机号" maxlength="11" />
          </view>
        </view>

        <!-- 验证码输入 -->
        <view class="input-group">
          <view class="input-wrapper">
            <input class="code-input" type="number" v-model="regCode" placeholder="请输入验证码" maxlength="4" />
            <view class="code-btn" @click="sendRegCode">
              {{ regCodeText }}
            </view>
          </view>
        </view>

        <!-- 邀请码输入 -->
        <view class="input-group">
          <view class="input-wrapper">
            <input class="text-input" type="text" v-model="inviteCode" placeholder="请输入邀请码（选填）" />
          </view>
        </view>

        <!-- 注册按钮 -->
        <view class="login-btn-wrapper">
          <button class="login-btn" @click="handleRegister">
            注册
          </button>
          <view class="switch-btn" @click="switchMode('login')">
            登录
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { userAPI } from '../../utils/api.js'
import { aesEcb } from '../../utils/crypto.js'

export default {
  data() {
    return {
      // 当前模式：login 或 register
      currentMode: 'login',
      // 登录类型：mobile 或 account
      loginType: 'mobile',

      // 手机号登录相关
      phone: '',
      code: '',
      countdown: 60,
      codeText: '获取验证码',

      // 账号登录相关
      username: '',
      password: '',
      captchaCode: '',
      captchaImage: '',
      captchaId: '',

      // 注册相关
      regUsername: '',
      regPassword: '',
      regPhone: '',
      regCode: '',
      regCountdown: 60,
      regCodeText: '获取验证码',
      inviteCode: ''
    }
  },

  mounted() {
    // 页面加载时获取图形验证码
    this.refreshCaptcha()
  },

  methods: {
    // 切换登录/注册模式
    switchMode(mode) {
      this.currentMode = mode
      if (mode === 'login') {
        this.loginType = 'mobile'
      } else if (mode === 'register') {
        // 切换到注册模式时，从缓存中读取邀请码
        const referralCode = uni.getStorageSync('referralCode')
        if (referralCode) {
          this.inviteCode = referralCode
        }
      }
    },

    // 切换登录类型
    switchLoginType(type) {
      this.loginType = type
      if (type === 'account') {
        this.refreshCaptcha()
      }
    },

    // 刷新图形验证码
    async refreshCaptcha() {
      try {
        const result = await userAPI.getCaptcha()
        if (result.code === 0 || result.success) {
          this.captchaImage = result.data?.image || result.image
          this.captchaId = result.data?.id || result.id
        }
      } catch (error) {
        console.error('获取图形验证码失败:', error)
      }
    },

    // 发送登录验证码
    async sendCode() {
      if (this.countdown < 60) return

      if (!this.phone || this.phone.length !== 11) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return
      }

      try {
        uni.showLoading({ title: '发送中...' })

        const result = await userAPI.sendMes({
          event: 'login',
          mobile: this.phone
        })

        uni.hideLoading()

        if (result.code === 0 || result.success) {
          uni.showToast({
            title: '验证码已发送',
            icon: 'success'
          })
          this.startCountdown()
        } else {
          uni.showToast({
            title: result.message || '发送失败，请重试',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('发送验证码失败:', error)
        uni.showToast({
          title: error.message || '发送失败，请重试',
          icon: 'none'
        })
      }
    },

    // 发送注册验证码
    async sendRegCode() {
      if (this.regCountdown < 60) return

      if (!this.regPhone || this.regPhone.length !== 11) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return
      }

      try {
        uni.showLoading({ title: '发送中...' })

        const result = await userAPI.sendMes({
          event: 'register',
          mobile: this.regPhone
        })

        uni.hideLoading()

        if (result.code === 0 || result.success) {
          uni.showToast({
            title: '验证码已发送',
            icon: 'success'
          })
          this.startRegCountdown()
        } else {
          uni.showToast({
            title: result.message || '发送失败，请重试',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('发送验证码失败:', error)
        uni.showToast({
          title: error.message || '发送失败，请重试',
          icon: 'none'
        })
      }
    },

    // 开始登录验证码倒计时
    startCountdown() {
      this.countdown = 60
      this.codeText = `稍等${this.countdown}秒`

      const timer = setInterval(() => {
        this.countdown--
        this.codeText = `稍等${this.countdown}秒`

        if (this.countdown <= 0) {
          clearInterval(timer)
          this.codeText = '获取验证码'
        }
      }, 1000)
    },

    // 开始注册验证码倒计时
    startRegCountdown() {
      this.regCountdown = 60
      this.regCodeText = `稍等${this.regCountdown}秒`

      const timer = setInterval(() => {
        this.regCountdown--
        this.regCodeText = `稍等${this.regCountdown}秒`

        if (this.regCountdown <= 0) {
          clearInterval(timer)
          this.regCountdown = 60
          this.regCodeText = '获取验证码'
        }
      }, 1000)
    },

    // 手机号登录
    async handleMobileLogin() {
      if (!this.phone || this.phone.length !== 11) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return
      }

      if (!this.code) {
        uni.showToast({
          title: '请输入验证码',
          icon: 'none'
        })
        return
      }

      try {
        uni.showLoading({ title: '登录中...' })

        const result = await userAPI.mobileLogin({
          mobile: this.phone,
          code: this.code
        })

        uni.hideLoading()

        if (result.code === 0) {
			this.handleLoginSuccess(result)
			if(result.data?.binding_url){
				window.location.href=result.data?.binding_url
			}
          
        } else {
          uni.showToast({
            title: result.message || '登录失败，请重试',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('登录失败:', error)
        uni.showToast({
          title: error.message || '登录失败，请重试',
          icon: 'none'
        })
      }
    },
	
	

    // 账号登录
    async handleAccountLogin() {
      if (!this.username) {
        uni.showToast({
          title: '请输入用户名',
          icon: 'none'
        })
        return
      }

      if (!this.password) {
        uni.showToast({
          title: '请输入密码',
          icon: 'none'
        })
        return
      }

      if (!this.captchaCode) {
        uni.showToast({
          title: '请输入验证码',
          icon: 'none'
        })
        return
      }

      try {
        uni.showLoading({ title: '登录中...' })

        const result = await userAPI.accountLogin({
          username: this.username,
          password: aesEcb.encrypt(this.password),
          cid: this.captchaId,
          code: this.captchaCode
        })

        uni.hideLoading()

        if (result.code === 0 || result.success) {
          this.handleLoginSuccess(result)
        } else {
          uni.showToast({
            title: result.message || '登录失败，请重试',
            icon: 'none'
          })
          // 刷新验证码
          this.refreshCaptcha()
        }
      } catch (error) {
        uni.hideLoading()
        console.error('登录失败:', error)
        uni.showToast({
          title: error.message || '登录失败，请重试',
          icon: 'none'
        })
        // 刷新验证码
        this.refreshCaptcha()
      }
    },

    // 处理登录成功
    handleLoginSuccess(result) {
      const token = result.data?.token || result.token
      const userInfo = result.data?.userInfo || result.data || {
        phone: this.phone || this.username,
        nickname: this.username || '用户' + (this.phone ? this.phone.substr(-6) : '')
      }

      if (token) {
        uni.setStorageSync('token', token)
        uni.setStorageSync('openid', result.data?.openid)
        uni.setStorageSync('userInfo', userInfo)

        uni.showToast({
          title: '登录成功',
          icon: 'success'
        })

        setTimeout(() => {
          uni.reLaunch({
            url: '/'
          })
        }, 1000)
      } else {
        uni.showToast({
          title: '登录失败：未获取到token',
          icon: 'none'
        })
      }
    },

    // 处理注册
    async handleRegister() {
      if (!this.regUsername) {
        uni.showToast({
          title: '请输入用户名',
          icon: 'none'
        })
        return
      }

      if (!this.regPassword) {
        uni.showToast({
          title: '请输入密码',
          icon: 'none'
        })
        return
      }

      if (!this.regPhone || this.regPhone.length !== 11) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return
      }

      if (!this.regCode) {
        uni.showToast({
          title: '请输入验证码',
          icon: 'none'
        })
        return
      }

      try {
        uni.showLoading({ title: '注册中...' })

        const result = await userAPI.register({
          username: this.regUsername,
          mobile: this.regPhone,
          password: aesEcb.encrypt(this.regPassword),
          code: this.regCode,
          invite_code: this.inviteCode || ''
        })

        uni.hideLoading()

        if (result.code === 0 || result.success) {
          uni.showToast({
            title: '注册成功',
            icon: 'success'
          })

          // 注册成功后切换到登录模式
          setTimeout(() => {
            this.countdown = 60
            this.currentMode = 'login'
            this.loginType = 'mobile'
            this.phone = this.regPhone
          }, 1500)
        } else {
          uni.showToast({
            title: result.message || '注册失败，请重试',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('注册失败:', error)
        uni.showToast({
          title: error.message || '注册失败，请重试',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #3A3052 0%, #4A4062 100%);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 40px 20px;
  position: relative;
  overflow: hidden;
}

.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: radial-gradient(circle at 30% 20%, rgba(240, 217, 181, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 70% 80%, rgba(143, 130, 168, 0.1) 0%, transparent 50%);
  z-index: 1;
}

.login-form {
  width: 100%;
  max-width: 320px;
  z-index: 2;
  position: relative;
}

.logo-section {
  text-align: center;
  margin-bottom: 60px;
}

.logo {
  font-size: 40px;
  font-weight: bold;
  color: #F0D9B5;
  margin-bottom: 8px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.subtitle {
  font-size: 20px;
  color: #8F82A8;
  font-weight: 300;
}

.switch-section {
  display: flex;
  background: rgba(74, 64, 98, 0.3);
  border-radius: 12px;
  padding: 4px;
  margin-bottom: 30px;
}

.switch-btn {
  text-align: center;
  padding: 12px 20px;
  color: #8F82A8;
  font-size: 20px;
  font-weight: 500;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.switch-btn.active {
  background: #E8B070;
  color: #333;
}

.login-type-section {
  display: flex;
  background: rgba(74, 64, 98, 0.3);
  border-radius: 12px;
  padding: 4px;
  margin-bottom: 30px;
}

.type-btn {
  flex: 1;
  text-align: center;
  padding: 10px 16px;
  color: #8F82A8;
  font-size: 18px;
  font-weight: 500;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.type-btn.active {
  background: rgba(232, 176, 112, 0.3);
  color: #F0D9B5;
}

.input-section {
  width: 100%;
}

.input-group {
  margin-bottom: 24px;
}

.input-wrapper {
  height: 50px;
  position: relative;
  display: flex;
  align-items: center;
  background: rgba(74, 64, 98, 0.8);
  border: 1px solid #675c86;
  border-radius: 12px;
  overflow: hidden;
  backdrop-filter: blur(10px);
}

.country-code {
  padding: 16px 12px;
  color: #F0C0A0;
  font-size: 20px;
  font-weight: 500;
  background: rgba(74, 64, 98, 0.5);
  border-right: 1px solid #52496D;
  min-width: 60px;
  text-align: center;
}

.phone-input {
  flex: 1;
  padding: 0 16px;
  background: transparent;
  border: none;
  color: #F0C0A0;
  font-size: 20px;
  outline: none;
}

.phone-input::placeholder {
  color: #8F82A8;
}

.code-input {
  flex: 1;
  padding: 0 16px;
  background: transparent;
  border: none;
  color: #FFFFFF;
  font-size: 20px;
  outline: none;
}

.code-input::placeholder {
  color: #8F82A8;
}

.text-input {
  flex: 1;
  padding: 0 16px;
  background: transparent;
  border: none;
  color: #F0C0A0;
  font-size: 20px;
  outline: none;
}

.text-input::placeholder {
  color: #8F82A8;
}

.code-btn {
  padding: 16px 20px;
  color: #8F82A8;
  font-size: 18px;
  background: rgba(74, 64, 98, 0.5);
  border-left: 1px solid #52496D;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.captcha-img {
  padding: 16px 20px;
  color: #8F82A8;
  font-size: 14px;
  background: rgba(74, 64, 98, 0.5);
  border-left: 1px solid #52496D;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 80px;
}

.captcha-img image {
  width: 60px;
  height: 30px;
  border-radius: 4px;
}

.captcha-img text {
  font-size: 16px;
}

.code-btn:active {
  background: rgba(74, 64, 98, 0.8);
  color: #F0D9B5;
}

.login-btn-wrapper {
  margin: 32px 0;
}

.login-btn {
  width: 100%;
  background: #E8B070;
  color: #333;
  border: none;
  border-radius: 12px;
  font-size: 22px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(232, 176, 112, 0.3);
}

.login-btn:active {
  background: #D4A060;
  transform: translateY(1px);
  box-shadow: 0 2px 8px rgba(232, 176, 112, 0.3);
}

.other-login {
  margin-top: 40px;
}

.divider {
  position: relative;
  text-align: center;
  margin: 20px 0;
}

.divider::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: #52496D;
}

.divider-text {
  padding: 0 16px;
  color: #8F82A8;
  font-size: 18px;
  position: relative;
  z-index: 1;
}
</style>
